package com.example.captcha.controller;

import com.example.redis.utils.CommonUtils;
import com.example.redis.utils.JsonData;
import com.google.code.kaptcha.Producer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author shawn
 */
@RestController
@RequestMapping("/api/v1")
public class CaptchaController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private Producer captchaProducer;
    /**
     * 临时使⽤10分钟有效，⽅便测试
     */
    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;

    /**
     * 获取图形验证码
     *
     * @param request
     * @param response
     */
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        //存储
        String captchaText = captchaProducer.createText();
        stringRedisTemplate.opsForValue().set(getCaptchaKey(request), captchaText, CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.getStackTrace();
        }
    }

    /**
     * 获取缓存的key
     *
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request) {
        String ip = CommonUtils.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        return "userservice:captcha:" + CommonUtils.MD5(ip + userAgent);
    }

    /**
     * ⽀持⼿机号、邮箱发送验证码
     * @return
     */
    @GetMapping("send_code")
    public JsonData
    sendRegisterCode(@RequestParam(value = "to", required = true)String to,
                     @RequestParam(value = "captcha", required = true)String captcha,
                     HttpServletRequest request){
        String key = getCaptchaKey(request);
        String cacheCaptcha = stringRedisTemplate.opsForValue().get(key);
        if(captcha!=null && cacheCaptcha!=null && cacheCaptcha.equalsIgnoreCase(captcha)) {
            stringRedisTemplate.delete(key);
            return JsonData.buildSuccess("校验成功");
        }else {
            return JsonData.buildError("图形验证码错误");
        }
    }
}
